﻿using Domain.Entity;
using Domain.Entity.Aprove;
using DtoFw;
using DtoFw.Query;
using DtoFw.Result;
using Repository.Base;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Util;

namespace Repository
{
    /// <summary>
    /// 出入库审批
    /// </summary>
    public class CasePhysicalApproveRepository : BaseRepository<CasePhysicalApproveEntity>
    {
        private readonly SnowFlakeGenerator worker;
        public CasePhysicalApproveRepository(SnowFlakeGenerator snowFlakeGenerator) : base(snowFlakeGenerator)
        {
            this.worker = snowFlakeGenerator;
        }

        public bool Insert(CasePhysicalApproveLogEntity log)
        {
            string sql = "insert into case_physical_approve_log(approveId,reason,remark,creatorId,creator,createTime)values(@approveId,@reason,@remark,@creatorId,@creator,@createTime);";
            return this.GetDb().Ado.ExecuteCommand(sql, new { log.ApproveId,log.Reason,log.Remark , log.Creator , log.CreateTime, log.CreatorId }) > 0;
        }

        public List<CasePhysicalApproveLogEntity> QueryLog(long approveId)
        {
            string sql = " select * from case_physical_approve_log where approveId="+ approveId;
            return this.GetDb().Ado.SqlQuery<CasePhysicalApproveLogEntity>(sql);
        }

    }

    public class CasePhysicalApproveListRepository : BaseRepository<CasePhysicalApproveListEntity>
    {
        private readonly SnowFlakeGenerator worker;
        public CasePhysicalApproveListRepository(SnowFlakeGenerator snowFlakeGenerator) : base(snowFlakeGenerator)
        {
            this.worker = snowFlakeGenerator;
        }
        public List<CasePhysicalApproveListEntity> GetList(long approveId)
        {
            return base.GetDb().Queryable<CasePhysicalApproveListEntity>().Where(v=>v.ApproveId == approveId).ToList();

        }
        public List<CaseEvidencePagerRespDto> QueryList(long approveId)
        {
            return base.GetDb().Queryable<CasePhysicalApproveListEntity, CasePhysicalEvidenceEntity>((t1, t2) => new JoinQueryInfos(
                JoinType.Left, t1.EvidenceId == t2.Id && !t1.IsDeleted && !t2.IsDeleted && t1.ApproveId == approveId))
                 .OrderBy((t1, t2) => t1.CreateTime, OrderByType.Desc)
                .Select((t1, t2) => new CaseEvidencePagerRespDto
                { 
                    Id = t1.Id,
                    EvidenceId = t2.Id,
                    EvidenceNo = t2.No,
                    EvidenceName = t2.Name,
                    EvidenceQuantity = t2.Quantity,
                    EvidenceClass = t2.Class,
                    EvidenceCategory = t2.Category,
                    EvidenceSource = t2.Source,
                    ExtractionPersonName = t2.ExtractionPersonName,
                    ExtractionDateTime = t2.ExtractionDateTime,
                    Location = t2.Location, 
                    RFID = t2.RFID, 
                    EvidenceClassName = t2.ClassName,
                    EvidenceCategoryName = t2.CategoryName,
                    EvidenceSourceName = t2.SourceName
                }).ToList();

        }

        /// <summary>
        /// 审批审核，查询可申请的物品
        /// </summary>
        /// <param name="reqDto"></param>
        /// <returns></returns>
        public Pager<CaseEvidencePagerRespDto> QueryCaseEvidences(EvidenceQueryReqDto reqDto)
        {
            int total = 0;
            Pager<CaseEvidencePagerRespDto> pager = new Pager<CaseEvidencePagerRespDto>();
            pager.Data = base.GetDb().Queryable<CaseEntity, CasePhysicalEvidenceEntity>((t1, t2) => new JoinQueryInfos(
                JoinType.Left, t1.Id == t2.CaseId))
                .Where((t1, t2) => !t1.IsDeleted && !t2.IsDeleted)
                .WhereIF(reqDto.CaseId > 0, t1 => t1.Id == reqDto.CaseId)
                .WhereIF(!string.IsNullOrWhiteSpace(reqDto.CaseNo), t1 => t1.CaseNo.Contains(reqDto.CaseNo))
                .WhereIF(!string.IsNullOrWhiteSpace(reqDto.CaseName), t1 => t1.CaseName.Contains(reqDto.CaseName))
                .WhereIF(!string.IsNullOrWhiteSpace(reqDto.InspectionNo), t1 => t1.InspectionNo.Contains(reqDto.InspectionNo))
                .WhereIF(reqDto.CaseTimeStart.HasValue && reqDto.CaseTimeEnd.HasValue,
                    (t1, t2) => t1.CaseTime > reqDto.CaseTimeStart && t1.CaseTime <= reqDto.CaseTimeEnd)
                .WhereIF(reqDto.CreateEndDateTime.HasValue && reqDto.CreateStartDateTime.HasValue,
                    (t1, t2) => t2.CreateTime > reqDto.CreateStartDateTime && t2.CreateTime <= reqDto.CreateEndDateTime)
                .WhereIF(!string.IsNullOrWhiteSpace(reqDto.EvidenceNo), (t1, t2) => t2.No.Contains(reqDto.EvidenceNo))
                .WhereIF(reqDto.Ids.Count > 0, (t1, t2) => !reqDto.Ids.Contains(t2.Id))
                .WhereIF(!string.IsNullOrWhiteSpace(reqDto.EvidenceName), (t1, t2) => t2.Name.Contains(reqDto.EvidenceName))
                .WhereIF(reqDto.EvidenceStatus > -1, (t1, t2) => t2.Status == reqDto.EvidenceStatus)
                .WhereIF(!string.IsNullOrWhiteSpace(reqDto.PersonName), (t1, t2) => t2.ExtractionPersonName.Contains(reqDto.PersonName))
                .WhereIF(reqDto.ExtractionDateTimeStart.HasValue && reqDto.ExtractionDateTimeEnd.HasValue,
                  (t1, t2) => t2.ExtractionDateTime > reqDto.ExtractionDateTimeStart && t2.ExtractionDateTime <= reqDto.ExtractionDateTimeEnd)
                 .OrderBy((t1, t2) => t1.CreateTime, OrderByType.Desc)
                .Select((t1, t2) => new CaseEvidencePagerRespDto()
                {
                    CaseId = t1.Id,
                    EvidenceId = t2.Id,
                    InspectionNo = t1.InspectionNo,
                    CaseName = t1.CaseName,
                    EvidenceNo = t2.No,
                    EvidenceName = t2.Name,
                    EvidenceQuantity = t2.Quantity,
                    EvidenceClass = t2.Class,
                    EvidenceCategory = t2.Category,
                    EvidenceSource = t2.Source,
                    ExtractionPersonName = t2.ExtractionPersonName,
                    ExtractionDateTime = t2.ExtractionDateTime,
                    Location = t2.Location,
                    EvSt = 0,//(EnumEvidenceStatus)t2.Status,
                    CaseNo = t1.CaseNo,
                    EvidenceClassName = t2.ClassName,
                    EvidenceCategoryName = t2.CategoryName,
                    EvidenceSourceName = t2.SourceName
                })
                .ToPageList(reqDto.Page, reqDto.PageSize, ref total);
            pager.TotalCount = total;
            if(total > 0)
            {
                foreach (var item in pager.Data)
                {
                    long evid = item.EvidenceId;
                    var first = base.GetDb().Queryable<CasePhysicalApproveListEntity>().Where(v => v.EvidenceId == evid && !v.IsDeleted).OrderBy(v=>v.Id,OrderByType.Desc).First();
                    if(first != null)
                    {
                        if(first.PassSt == 0)
                        {
                            //未审核
                            item.EvSt = 1;
                        }
                        else if(first.PassSt == 1 && !first.IsUsed)
                        {
                            //已审核，未使用
                            item.EvSt = 2;
                        }
                    }
                }
            }
            return pager;
        }

        /// <summary>
        /// 案件物品分页
        /// </summary>
        /// <param name="reqDto"></param>
        /// <returns></returns>
        public List<CasePhysicalApproveListEntity> CheckEvidenceAuditState(List<long> ids, string ty)
        {
            string sql = $@" SELECT s2.*
                               from case_physical_approve s1 
                               join case_physical_approve_list s2 on s1.id=s2.approveId 
                              where s1.ty='{ty}'
	                              and s1.IsDeleted=0
		                            and s2.IsDeleted=0
		                            and s2.isUsed=0
		                            and s2.passst=1 
                                    and s2.evidenceId in({string.Join(",", ids)})";
            var lst = base.GetDb().SqlQueryable<CasePhysicalApproveListEntity>(sql).ToList();
            return lst;
        }
        public void UseEvidenceApprove(List<long> evidenceIds, string ty, string user, long userid)
        {
            var lst = CheckEvidenceAuditState(evidenceIds, ty).ToList();
            foreach (var item in lst)
            {
                item.IsUsed = true;
                item.Modifyer = user;
                item.ModifyerId = userid;
                item.ModifyerTime = DateTime.Now;
                GetDb().Updateable<CasePhysicalApproveListEntity>(item).ExecuteCommand();
            }
        }
    }

}
